<script setup lang="ts">
import type {Cropper, CropperResult} from './typing';

import {ref} from 'vue';
import {Upload, message} from 'ant-design-vue';
import {BasicAvatar, BasicButton, BasicIcon} from '#/components/shadcn-ui';
import {useModal} from '#/ui-kit';
import {dataURLtoBlob} from '#/utils';

// import {upload} from '#/api/file';

import CropperImage from './cropper-image.vue';

const emits = defineEmits(['update']);

const cropper = ref<Cropper>();
const avatar = ref('');
const preview = ref('');
let filename = '';
let scaleX = 1;
let scaleY = 1;

const [Modal, modalApi] = useModal({
  confirmText: '确认并上传',
  closeOnClickModal: false,
  closeOnPressEscape: false,
  fullscreenButton: false,
  onOpenChange: (isOpen) => {
    if (isOpen) {
      avatar.value = modalApi?.getData()?.avatar;
    }
  },
  onConfirm: () => {
    handleConfirm();
  }
});

const handleConfirm = async () => {
  modalApi.setState({confirmLoading: true});
  try {
    const blob = dataURLtoBlob(preview.value);
    message.warn('上传功能接口暂未实现，请至 cropper-modal.handleConfirm() 中自行实现');
    // await upload({file: blob, filename}).then(res => {
    //   emits('update', res.url);
    //   modalApi.close();
    // });
  } finally {
    modalApi.setState({confirmLoading: false});
  }
}

const handleBeforeUpload = (file) => {
  const reader = new FileReader();
  reader.readAsDataURL(file);
  avatar.value = '';
  preview.value = '';
  reader.onload = function (e) {
    avatar.value = (e.target?.result as string) ?? '';
    filename = file.name;
  };
  return false;
}

const handleToolbar = (event, arg) => {
  if (event === 'scaleX') {
    scaleX = arg = scaleX === -1 ? 1 : -1;
  }
  if (event === 'scaleY') {
    scaleY = arg = scaleY === -1 ? 1 : -1;
  }
  (cropper?.value as any)?.[event]?.(arg);
}

const handleReady = (instance) => {
  cropper.value = instance;
}

const handleCropend = ({imgBase64}: CropperResult) => {
  preview.value = imgBase64;
}
</script>
<template>
  <Modal>
    <div class="cropper-modal-wrapper">
      <div class="cropper-modal-left">
        <div class="cropper-image-wrapper">
          <CropperImage v-if="avatar" :src="avatar" :height="300" @reday="handleReady" @cropend="handleCropend"/>
        </div>
        <div class="cropper-toolbar">
          <Upload :show-upload-list="false" accept="image/*" :before-upload="handleBeforeUpload">
            <BasicButton size="icon" class="h-[24px] w-[30px]"
                         v-tippy="{content: '选择图片', placement: 'bottom'}">
              <BasicIcon class="h-[14px] w-[14px]" icon="ant-design:upload-outlined"/>
            </BasicButton>
          </Upload>

          <div class="grid gap-1 grid-cols-7 gap-x-3">
            <BasicButton size="icon" class="h-[24px] w-[30px]" :disabled="!avatar"
                         v-tippy="{content: '重置', placement: 'bottom'}" @click="handleToolbar('reset')">
              <BasicIcon class="h-[14px] w-[14px]" icon="ant-design:reload-outlined"/>
            </BasicButton>

            <BasicButton size="icon" class="h-[24px] w-[30px]" :disabled="!avatar"
                         v-tippy="{content: '逆时针旋转', placement: 'bottom'}" @click="handleToolbar('rotate', -45)">
              <BasicIcon class="h-[14px] w-[14px]" icon="ant-design:rotate-left-outlined"/>
            </BasicButton>

            <BasicButton size="icon" class="h-[24px] w-[30px]" :disabled="!avatar"
                         v-tippy="{content: '顺时针旋转', placement: 'bottom'}" @click="handleToolbar('rotate',45)">
              <BasicIcon class="h-[14px] w-[14px]" icon="ant-design:rotate-right-outlined"/>
            </BasicButton>

            <BasicButton size="icon" class="h-[24px] w-[30px]" :disabled="!avatar"
                         v-tippy="{content: '水平翻转', placement: 'bottom'}" @click="handleToolbar('scaleX')">
              <BasicIcon class="h-[14px] w-[14px]" icon="vaadin:arrows-long-h"/>
            </BasicButton>

            <BasicButton size="icon" class="h-[24px] w-[30px]" :disabled="!avatar"
                         v-tippy="{content: '垂直翻转', placement: 'bottom'}" @click="handleToolbar('scaleY')">
              <BasicIcon class="h-[14px] w-[14px]" icon="vaadin:arrows-long-v"/>
            </BasicButton>

            <BasicButton size="icon" class="h-[24px] w-[30px]" :disabled="!avatar"
                         v-tippy="{content: '放大', placement: 'bottom'}" @click="handleToolbar('zoom', 0.1)">
              <BasicIcon class="h-[14px] w-[14px]" icon="ant-design:zoom-in-outlined"/>
            </BasicButton>

            <BasicButton size="icon" class="h-[24px] w-[30px]" :disabled="!avatar"
                         v-tippy="{content: '缩小', placement: 'bottom'}" @click="handleToolbar('zoom', -0.1)">
              <BasicIcon class="h-[14px] w-[14px]" icon="ant-design:zoom-out-outlined"/>
            </BasicButton>
          </div>
        </div>
      </div>
      <div class="cropper-modal-right">
        <div class="cropper-preview">
          <img :src="preview" v-if="preview" alt="avatar">
        </div>
        <div class="cropper-preview-group">
          <BasicAvatar :src="preview" class="w-[38px] h-[38px]"/>
          <BasicAvatar :src="preview" class="w-[46px] h-[46px]"/>
          <BasicAvatar :src="preview" class="w-[62px] h-[62px]"/>
          <BasicAvatar :src="preview" class="w-[78px] h-[78px]"/>
        </div>
      </div>
    </div>
  </Modal>
</template>

<style scoped>
.cropper-modal-wrapper {
  display: flex;

  .cropper-modal-left, .cropper-modal-right {
    height: 340px;
  }

  .cropper-modal-left {
    width: 55%;

    .cropper-image-wrapper {
      height: 300px;
      background: #eee linear-gradient(
          45deg,
          rgb(0 0 0 / 25%) 25%,
          transparent 0,
          transparent 75%,
          rgb(0 0 0 / 25%) 0
      ),
      linear-gradient(
          45deg,
          rgb(0 0 0 / 25%) 25%,
          transparent 0,
          transparent 75%,
          rgb(0 0 0 / 25%) 0
      ) 0 0, 12px 12px;
      background-size: 24px 24px;
    }

    .cropper-toolbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 10px;
    }
  }

  .cropper-modal-right {
    width: 45%;

    .cropper-preview {
      width: 220px;
      height: 220px;
      margin: 0 auto;
      overflow: hidden;
      border-radius: 50%;

      img {
        width: 100%;
        height: 100%;
      }
    }

    .cropper-preview-group {
      display: flex;
      padding-top: 8px;
      margin-top: 8px;
      justify-content: space-around;
      align-items: center;
    }
  }
}
</style>